package org.vt.ece4564.pcw.textinclass;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.telephony.SmsManager;
import android.util.Log;

public class DownloadMessagesTask extends TimerTask {
	
	Context context_;
	Cookie cookie_;
	
	private final String URL = "http://pcw-textinclass.appspot.com/getMessagesAndroid";
	
	public DownloadMessagesTask(Context context, Cookie cookie) {
		super();
		context_ = context;
		cookie_ = cookie;
	}

	@Override
	public void run() {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL);
			
			get.addHeader("Cookie", cookie_.getName() + "=" + cookie_.getValue());
			
			HttpResponse response = client.execute(get);
			
			if (response.getStatusLine().getStatusCode() != 200) {
				if (response.getStatusLine().getStatusCode() != 200) {
					Log.d("DownloadMessagesTaskError", response.getStatusLine().toString());
					return;
				}
			}
			
			String line;
			String responseString = "";
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			
			while ((line = reader.readLine()) != null) {
				responseString += line;
			}
			
			if (responseString.contains("Error")) {
				Log.d("Error", responseString);
			}
			
			MessageXmlParser parser = new MessageXmlParser();
			Map<String, List<String>> data = parser.parse(responseString);
			
			List<String> numbers = new ArrayList<String>(data.keySet());
			
			// Need to fix this so it will update the sms app
			
			SmsManager smsManager = SmsManager.getDefault();
			
			for (String number : numbers) {
				List<String> messages = data.get(number);
				
				for (String message : messages) {
					smsManager.sendTextMessage(number, null, message, null, null);
				}
			}
			
		} catch (Exception e) {
			Log.d("CatchMessageTimerTaskException", e.toString());
		}
	}

}
